var websocket = null;
var userid;
var toIds;


function openWebSocket(id) {

    userid = id;
    console.log("userid:" + userid);
    if (userid == null) {
        return;
    }
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {

        websocket = new WebSocket("ws://192.168.17.103:8011/yixian/websocket/{" + userid + "}");
    } else {
        console.log('Not support websocket')
        setMessageInnerHTML("您的浏览器不支持WebSocket", 0);
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("error", 0);
        document.getElementById('reLoad').style.visibility = "visible";
    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        setMessageInnerHTML("上线", 4);
        document.getElementById('reLoad').style.visibility = "hidden";

    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {

        var obj = JSON.parse(event.data);
        console.log(obj);
        if (obj.fromUser.id == userid) {
            return;
        }


        var html = obj.fromUser.name + ": " + obj.data.test;
        var item = '<div class="left">' + html + '</div> <br/>';
        saveMessage(userid, obj.fromUser.id, item);

        if (toIds != null && toIds.length > 0 && toIds[0] == obj.fromUser.id) {
            //当前聊天页面,显示。
            setMessageInnerHTML(obj.fromUser.name + ": " + obj.data.test, 1);
        } else {
            //不是当前聊天的人
            var element = document.getElementById(obj.fromUser.id + "");
            element.style.visibility = "visible";
            var num = element.innerHTML;
            if (num == null || num == "") {
                element.innerHTML = "1";
            } else {

                if (num != "99+") {
                    var n = parseInt(num) + 1;
                    if (n > 99) {
                        element.innerHTML = "99+";
                    } else {
                        element.innerHTML = n + "";
                    }
                }

            }
        }

    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("下线", 3);
        //openWebSocket(userid);
        document.getElementById('reLoad').style.visibility = "visible";
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }

    $('#text').bind('keyup', function (event) {

        if (event.keyCode == "13") {
            //回车执行查询
            send();
        }
    });
}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML, style) {
    var msgDiv = document.getElementById('message');
    if (style == 0) {
        //显示历史信息
        msgDiv.innerHTML += innerHTML;
    } else if (style == 1) {
        msgDiv.innerHTML += '<div class="left">' + innerHTML + '</div> <br/>';
    } else if (style == 2) {
        if (innerHTML.length > 40) {
            msgDiv.innerHTML += '<div  class="right">' + innerHTML + '</div> <br/>';
        } else {
            msgDiv.innerHTML += '<div  class="rightright">' + innerHTML + '</div> <br/>';
        }

    } else if (style == 3) {

        $('#state').html('<span  style="color: darkgray;">' + innerHTML + '</span>');
    } else if (style == 4) {
        $('#state').html('<span  style="color: coral">' + innerHTML + '</span>');
    }
    msgDiv.scrollTop = msgDiv.scrollHeight;
}

//关闭连接
function closeWebSocket() {
    if (websocket != null)
        websocket.close();
}

//改变聊天的对象
function changeTalk(array) {
    console.log(array);
    toIds = [];
    $.each(array, function (i, item) {
        toIds.push(item.id);
    });
    addTalker(array);

    //取消提示数字
    var warnNum = document.getElementById(toIds[0] + "");
    warnNum.innerHTML = "";
    warnNum.style.visibility = "hidden";


    //显示历史聊天记录  并显示
    //user 收到的话
    findOldMessage(userid, array[0].id);
    //user 发出的话
    findOldMessage(array[0].id, userid);
}

function showOldMessage(OldMessAge) {
    console.log("findOldMessage");
    console.log(OldMessAge)
    if (OldMessAge != null) {
        setMessageInnerHTML(OldMessAge, 0);
    }

}

//更改聊天对象的标签
function addTalker(talker) {
    var html = '';
    $('#message').empty();
    $('#current_talk').empty();
    for (var i = 0; i < talker.length; i++) {
        if (i > 10) {
            html += "...";
            break;
        }
        html = html + '<span class="label label-success talkerLable">' + talker[i].name + '</span>';
    }
    console.log(html);
    $('#current_talk').html('').append(html);
}

function iGetInnerText(testStr) {
    // var resultStr = testStr.replace(/\ +/g, ""); //去掉空格
    // resultStr = resultStr.replace(/[ ]/g, "");    //去掉空格
    var resultStr = testStr.replace(/(^\s*)|(\s*$)/g, "");//去点两端的空格
    resultStr = resultStr.replace(/[\r\n]/g, ""); //去掉回车换行
    return resultStr;
}

//发送消息
function send() {
    var message = document.getElementById('text').value;
    message = iGetInnerText(message);
    var type = 0;
    if ("" == message) {
        document.getElementById('text').value = message;
        return;
    }

    if (toIds == null || toIds.length == 0) {
        console.log("toids is null ");
        return;
    }
    if (toIds.length > 1) {
        type = 1;
    }
    var jsonStr = JSON.stringify(toIds);
    var json = "{ \"type\": \"" + type + "\", \"fromId\": \"" + userid + "\", \"toIds\": " + jsonStr + ",\"groupId\":\"\" ,\"data\":{ \"test\":\"" + message + "\"}}";

    websocket.send(json);

    //保存自己的话
    var html = "我 : " + message;
    var item = "";

    if (html.replace(/[ ]/g, "").length > 40) {
        item = '<div  class="right">' + html.replace(/[ ]/g, "&nbsp;") + '</div><br/>';
    } else {
        item = '<div  class="rightright">' + html.replace(/[ ]/g, "&nbsp;") + '</div><br/>';
    }
    saveMessage(userid, toIds[0], item);

    //显示自己的话
    setMessageInnerHTML(item, 0);
    document.getElementById('text').value = "";
}